#!/usr/bin/env bash

# @license
# Copyright 2022-2025 Matter.js Authors
# SPDX-License-Identifier: Apache-2.0

# Creates a binary using build-examples.py.  Strips, installs into /dist/bin and removes build artifacts

set -e

NAME=$1
OPTIONS=ipv6only-no-ble-no-wifi-no-thread-no-shell-platform-mdns-clang

die() {
    echo $1 >&2
    exit 1
}

if [ -z "$NAME" ]; then
    die "No name supplied"
fi

if [ "$SKIP_APPS" -a "$NAME" != "chip-tool" ]; then
    echo "Skipping app $NAME"
    exit
fi

case "$TARGETPLATFORM" in
    "linux/amd64")
        CPU=x64
        ;;
    "linux/arm64")
        CPU=arm64
        ;;
    *)
        die "Unrecognized target platform \"$TARGETPLATFORM\""
esac

# /connectedhomeip/scripts/build/build_examples.py \
#     --target linux-$CPU-$NAME-$OPTIONS \
#     build

TARGET=linux-$CPU-$NAME-$OPTIONS

mkdir out

GN_ARGS=(
    chip_inet_config_enable_ipv4=false
    chip_config_network_layer_ble=false
    chip_enable_ble=false
    chip_enable_wifi=false
    chip_enable_openthread=false
    chip_build_libshell=false
    is_clang=true
    chip_mdns='"platform"'
    matter_enable_tracing_support=false
    matter_trace_config='"///src/tracing/none"'
    matter_commandline_enable_perfetto_tracing=false
)

gn gen out \
    --fail-on-unused-args \
    --add-export-compile-commands=* \
    --root=examples/$NAME \
    --args="${GN_ARGS[*]}"

ninja -C out $NAME

BINPATH="$(find "out" -type f -executable)"
if [ ! -x "$BINPATH" ]; then
    die "Could not identify executable for target \"$TARGET\""
fi

strip "$BINPATH"
mkdir -p /dist/bin
mv "$BINPATH" /dist/bin

#rm -rf "out/$TARGET"
rm -rf out
